package com.iniapp.app.jsf;

import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import javax.faces.context.FacesContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class JsfSecurityUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(JsfSecurityUtil.class);
	private static final String DEFAULT_ALGORITHM = "MD5";
	private static final int NUM_SALT_BYTES = 8;
	
	public static Identity getCurrentIdentity(){
		 Identity identity = null;
		 try {
				FacesContext context = FacesContext.getCurrentInstance();
				identity = (Identity) context.getApplication().evaluateExpressionGet(context, "#{identity}", Identity.class);
				
				if (identity != null) {
					return identity;
				} else {
					return null;
				}
			} catch (Exception e) {
				logger.error("can not get Identity in current context.", e);	
				return null;
			}
	} 
	
	public static Integer getCurrentUserId(){
		Identity id = getCurrentIdentity();
        if(id!=null){
        	return id.getUserId(); 
        }else{
        	return null;
        }
	} 
	
	private static final Set<String> ignoredURLs = new HashSet<String>();
	static{
//		ignoredURLs.add("/index");
//		ignoredURLs.add("/myarea");
//		ignoredURLs.add("/myInfo");
//		ignoredURLs.add("/notes");
//		ignoredURLs.add("/userRegistration");
		ignoredURLs.add("/login");
		ignoredURLs.add("/common/");	
//		ignoredURLs.add("/pprSelect");	
//		ignoredURLs.add("/m/");	
		//test pages
		ignoredURLs.add("/test/");
	}

	public static Set<String> getIgnoredURLs() {
		return ignoredURLs;
	}

	public static boolean isIgnored(String url){
		for(String iurl: getIgnoredURLs()){
			if(url.startsWith(iurl)){
				return true;
			}
		}
		return false;
	}

	private JsfSecurityUtil() { }
	
	/*public static String createPasswordHash(String password) {
		return createPasswordHash(password, null);
	}*/
	
	public static Locale getCurrentLocale(){
		if(FacesContext.getCurrentInstance()==null) return Locale.CHINA;//Sam added temporary for Rest Service
		return FacesContext.getCurrentInstance().getViewRoot().getLocale();
	}
	
	public static String getCurrentLocaleString(){
		if(getCurrentLocale()!=null){
			return getCurrentLocale().toString();
		}else{
			return getDefaultLocale().toString();
		}
	}
	
	public static Locale getDefaultLocale(){
		return FacesContext.getCurrentInstance().getApplication().getDefaultLocale();
	}
	
	
	public static String getRandomPassword(){
		return PasswordGenerator.getPassword(6);
	}
	

	public static boolean isUrlMatch(String currentUrl, List<String> urls){
		boolean match = false;
		for(String url:urls){
			if(currentUrl.startsWith(url)){
				match = true;
				break;
			}
		}
		return match;
	}

	public static boolean isActionGranted(String action, List<String> actions){
		
			return true;
		
	}
}
